﻿using CefSharp;
using CefSharp.WinForms;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;

namespace MrytPub
{
    public partial class PubForm : Form
    {
        public delegate void myDelegate(string str);

        public ChromiumWebBrowser browser;
        DateTime curDay;
        private string url;
        public void InitBrowser()
        {
            //object p = Cef.GetGlobalCookieManager()..SetStoragePath(Environment.CurrentDirectory, true);
            browser = new ChromiumWebBrowser(url);
            this.pn.Controls.Add(browser);
            browser.Dock = DockStyle.Fill;
            browser.LifeSpanHandler = new OpenPageSelf();
        }

        public PubForm(string url, DateTime curDay)
        {
            this.url = url;
            this.curDay = curDay;
            InitializeComponent();
        }

        private void PubForm_Load(object sender, EventArgs e)
        {
            InitBrowser();
            //curDay = DateTime.Now;
            tb_pubdate.Text = curDay.ToString("yyyy-MM-dd");
        }

        public void _invoke_myDelegate(String msg)
        {
            lb_msg.Text = msg;
            browser.Load(MrytPub.Properties.Settings.Default.listurl);
        }

        public void _invoke_show_question(String html)
        {
            ShowForm pubForm = new ShowForm(html);
            pubForm.Show();
        }

        private void bt_pub_Click(object sender, EventArgs e)
        {
            lb_msg.Text = "添加习题";
            var task02 = browser.GetMainFrame().GetSourceAsync();
            task02.ContinueWith(t => {
                if (!t.IsFaulted)
                {
                    string html = t.Result; //HtmlHelper.TakeHtml(t.Result);

                    Regex jre = new Regex(" question: (.*?)\n");
                    Match jmc = jre.Match(html);

                    //Console.WriteLine(jmc.Value);

                    var result = JsonConvert.DeserializeObject<Question>(jmc.Groups[1].Value);

                    string s = JsonHelper.question2Html(result);
                    /*
                    StringBuilder sb = new StringBuilder();
                    sb.Append("<div class='question'>");
                    {
                        sb.Append("<div class='question_text'>");
                        sb.Append(result.question_text);
                        sb.Append("</div>");
                        if (result.list != null)
                        {
                            sb.Append("<ol class='child_question'>");
                            foreach (Question q in result.list)
                            {
                                sb.Append("<li class='child_item'>");
                                sb.Append(q.question_text);
                                sb.Append("</li>");
                            }
                            sb.Append("</ol>");
                        }
                    }
                    sb.Append("</div>");
                    var msg = Post(sb.ToString());
                    */
                    var msg = Post(s);

                    this.BeginInvoke(new myDelegate(_invoke_myDelegate), msg);
                }
            });
        }


        public string Post(string str)
        {
            StringBuilder postData = new StringBuilder();
            postData.Append("question=" + HttpUtility.UrlEncode(str, Encoding.UTF8));
            postData.Append("&publish_date=" + tb_pubdate.Text);
            byte[] sendData = Encoding.UTF8.GetBytes(postData.ToString());

            WebClient wc = new WebClient();
            wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            wc.Headers.Add("ContentLength", sendData.Length.ToString());
            string url = MrytPub.Properties.Settings.Default.puburl;
            byte[] recData = wc.UploadData(url, "POST", sendData);
            return Encoding.UTF8.GetString(recData);
        }


        private void bt_nextday_Click(object sender, EventArgs e)
        {
            curDay = curDay.AddDays(1);
            tb_pubdate.Text = curDay.ToString("yyyy-MM-dd");
        }

        private void bt_preday_Click(object sender, EventArgs e)
        {
            curDay = curDay.AddDays(-1);
            tb_pubdate.Text = curDay.ToString("yyyy-MM-dd");
        }

        private void bt_讲解_Click(object sender, EventArgs e)
        {
            var task02 = browser.GetMainFrame().GetSourceAsync();
            task02.ContinueWith(t => {
                if (!t.IsFaulted)
                {
                    string html = t.Result;
                    Regex jre = new Regex(" question: (.*?)\n");
                    Match jmc = jre.Match(html);
                    var result = JsonConvert.DeserializeObject<Question>(jmc.Groups[1].Value);
                    string s = JsonHelper.question2Html(result);
                    this.BeginInvoke(new myDelegate(_invoke_show_question), s);
                }
            });
        }
    }
}
